package cc.jweb.adai.interceptor;

import cc.jweb.adai.web.system.log.service.SysLogService;
import cc.jweb.adai.web.system.sys.model.SysLog;
import cc.jweb.boot.db.Db;
import cc.jweb.boot.security.session.account.JwebSecurityAccount;
import cc.jweb.boot.security.utils.JwebSecurityUtils;
import cc.jweb.boot.utils.lang.StringUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import io.jboot.utils.RequestUtil;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 系统日志记录拦截器
 *
 * @author imlzw
 * @since 2021-04-19
 */
public class SyslogInterceptor implements Interceptor {

    // 保存日志线程池，
    ExecutorService executorService = Executors.newSingleThreadExecutor();


    @Override
    public void intercept(Invocation inv) {
        inv.invoke();
        try {
            SysLog syslog = SysLogService.service.getSyslog();
            if (syslog != null) {
                JwebSecurityAccount account = JwebSecurityUtils.getAccount();
                if (account != null) {
                    syslog.setUserId(Integer.parseInt(account.getUid()));
                }
                syslog.setLogDatetime(new Date());
                syslog.setLogUrl(inv.getActionKey());
                syslog.setLogIp(RequestUtil.getIpAddress(inv.getController().getRequest()));
                // syslog
                executorService.submit(() -> {
                    if (StringUtils.isBlank(syslog.getLogCategory())) {
                        String operName = Db.queryStr("select oper_name from sys_oper where oper_path = ?", inv.getControllerPath());
                        if (StringUtils.notBlank(operName)) {
                            syslog.setLogCategory(operName);
                        } else {
                            syslog.setLogCategory("未知");
                        }
                    }
                    syslog.save();
                });
            }
        } finally {
            SysLogService.service.clearSyslog();
        }

    }

}
